package com.example.yls.inote.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.example.yls.inote.models.Note;

import java.util.ArrayList;
import java.util.List;

import static android.provider.BaseColumns._ID;
import static com.example.yls.inote.db.NotesContract.NoteTable.BODY;
import static com.example.yls.inote.db.NotesContract.NoteTable.CREATED_AT;
import static com.example.yls.inote.db.NotesContract.NoteTable.TITLE;
import static com.example.yls.inote.db.NotesContract.NoteTable._TABLE_NAME;

/**
 * Created by My Family on 2018/6/10.
 */

public class NoteDatabase {

    private NotesOpenHelper helper;


    public NoteDatabase(Context context) {
        helper =  new NotesOpenHelper(context);
    }

    public List<Note> getAll(){
        Cursor cursor = helper.getReadableDatabase().query(_TABLE_NAME,
                null,
                null,
                null,
                null,
                null,
                CREATED_AT);
        List<Note> retval = allFromCursor(cursor);
        cursor.close();
        return retval;
    }

    private List<Note> allFromCursor(Cursor cursor) {
        List<Note> retval = new ArrayList<>();
        while (cursor.moveToNext()) {
            retval.add(fromCursor(cursor));
        }
        return retval;
    }

    private Note fromCursor(Cursor cursor) {
        Note note = new Note();
        note.setId(cursor.getInt(cursor.getColumnIndexOrThrow(_ID)));
        note.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(TITLE)));
        note.setBody(cursor.getString(cursor.getColumnIndexOrThrow(BODY)));
        note.setCreatedAt(cursor.getLong(cursor.getColumnIndexOrThrow(CREATED_AT)));

        return note;
    }

    public void insert(Note... notes) {
        List<ContentValues> values = fromNotes(notes);
        SQLiteDatabase db = helper.getWritableDatabase();
        db.beginTransaction();
        try{
            for(ContentValues value :values){
                db.insert(_TABLE_NAME,null,value);
            }
            db.setTransactionSuccessful();
        }finally {
            db.endTransaction();
        }

    }

    private List<ContentValues> fromNotes(Note[] notes) {
        List<ContentValues> values = new ArrayList<>();
        for(Note note : notes){
            values.add(fromNote(note));
        }
        return values;
    }

    private ContentValues fromNote(Note note) {
        ContentValues values = new ContentValues();
        int id = note.getId();
        if(id != -1){
            values.put(_ID,id);
        }
        if (id != -1) {
            values.put(_ID, id);
        }
        values.put(TITLE,note.getTitle());
        values.put(BODY,note.getBody());
        values.put(CREATED_AT,note.getCreatedAt());
        return values;
    }
}
